<?php
/**
 * 用户管理中心
 *
 */
class UserAction extends BaseAction {

	public function _initialize() {
		parent::_initialize();
	}

	//        public function msg () {
	//                $group = D('SystemGroup')->getGroupList();
	//                $this->assign('smileList',$this->getSmile($this->opts['ico_type']));
	//                $this->assign('smilePath',$this->getSmilePath($this->opts['ico_type']));
	//                $this->assign('group',$group);
	//                $this->display();
	//        }
	//        public function doSend() {
	//                //获取用户登陆ID
	//                if($_POST['type'] == 1) {
	//                        $this->doSendMsg();
	//                }else {
	//                        $this->doSendEmail();
	//                }
	//                $this->assign('jumpUrl',__URL__.'/msg');
	//                $this->success('发送成功');
	//        }
	//        public function doSendMsg() {
	//                $toUserIds =$this->__GroupGetUser();
	//                $dao = D("Msg");
	//                $r = $dao->create();
	//                if(false === $r) $this->error($dao->getError());
	//
	//                $dao->cTime = time();
	//                $dao->fromUserId = $this->uid;
	//                $title_data['title'] = $dao->subject;
	//                foreach($toUserIds as $uid) {
	//                        $dao->toUserId = $uid;
	//                        $r = $dao->add();
	//                        //通知
	//                        $cate = "message";
	//                        $this->api->notify_send($uid,$type,$title_data,$body_data,$url,$cate);
	//                }
	//                return true;
	//        }

	//        public function doSendEmail() {
	//                $toUids = $this->__GroupGetUser();
	//                $dao = D('User');
	//                $title = $_POST['subject'];
	//                $content = $_POST['content'];
	//                $mid = $this->uid;
	//                foreach ($toUids as $value) {
	//                        $temp = $dao->where('id='.$value)->field('email')->find();
	//                        $email[] = $temp['email'];
	//                }
	//                return $this->api->SaveEmail_saveEmail($email,$title,$content,$mid);
	//        }
	private function __GroupGetUser() {
		$gid = $_POST['gid'];
		return $toUserIds = D('User')->getGroupUsers($gid);
	}
	public function userscore(){
		$setScore = $this->setCredit();
		$this->assign('setScore',$setScore);
		$this->assign('grounlist',D('SystemGroup')->findall());
		$this->display();
	}
	/*
	* 用户列表
	*
	*/
	public function index() {
		$pUser	=	D('User');
		//查询条件
		if(!empty($_REQUEST['fullname'])) $map['fullname'] = array('like','%'.$_REQUEST['fullname'].'%');
		if(!empty($_REQUEST['searchuid']))  $map['uid']    = array('in',explode(',',$_REQUEST['searchuid']));
		if(!empty($_REQUEST['uname']))  $map['uname']      = $_REQUEST['uname'];
		if($_REQUEST['groupid']!=9)  $map['uid']      = array('in',model('UserGroup')->getGroupUsers($_REQUEST['groupid']));


		//排序
		$field = ($_REQUEST['field'])?$_REQUEST['field']:'uid';
		$order = ($_REQUEST['order'])?$_REQUEST['order']:'DESC';
		$limit = ($_REQUEST['limit'])?$_REQUEST['limit']:'20';

		$arrOrder['field'] = $field;
		$arrOrder['order'] = $order;
		$arrOrder['limit'] = $limit;

		if($_POST) {
			Session::set('userSearch',serialize($map));
			Session::set('userOrder',serialize($arrOrder));
			$sorder = $arrOrder;
		}elseif (isset($_GET['p'])) {
			if(Session::get('userSearch')) {
				$map = unserialize(Session::get('userSearch'));
				$sorder = unserialize(Session::get('userOrder'));
			}else {
				$map = '';
				$sorder = $arrOrder;
			}
		}else {
			$map = '';
			$sorder = $arrOrder;
			unset($_SESSION['userSearch']);
			unset($_SESSION['userOrder']);
		}

		$this->assign('grounlist',D('SystemGroup')->findall());
		$this->assign('commend',$map['commend']);
		$this->assign('fullname',$_REQUEST['fullname']);

		if($map['searchuid']) {
			$this->assign('searchuid',implode(',',$map['searchuid'][1]));
		}

		$this->assign('uname',$map['uname']);

		$this->assign('groupid',($_REQUEST['groupid'])?$_REQUEST['groupid']:9);
		$this->assign('status',$map['active']);

		$this->assign('field',$sorder['field']);
		$this->assign('order',$sorder['order']);
		$this->assign('limit',$sorder['limit']);
		$list = $pUser->where( $map )->order( $sorder['field'].' '.$sorder['order'] )->findPage($sorder['limit']) ;

		$this->assign('pages',$list['html']);
		$this->assign('list',$list['data']);
		$this->assign('count',$list['count']);
		$this->assign('grouplist',model('UserGroup')->getGroups());
		$this->display();
	}
	public function doSetCredit(){
		//查询条件
		set_time_limit(0);
		if(!empty($_REQUEST['name'])) $map['name'] = array('like','%'.$_REQUEST['name'].'%');
		if(!empty($_REQUEST['uid']))  $map['id']   = array('in',explode(',',$_REQUEST['uid']));
		if(!empty($_REQUEST['email']))  $map['email']   = $_REQUEST['email'];
		if(!empty($_REQUEST['commend'])) $map['commend']   = intval($_REQUEST['commend']);
		if($_REQUEST['status']!='9') $map['active']        = $_REQUEST['status'] ;
		if($_REQUEST['groupid']!='9') $map['admin_level']  = $_REQUEST['groupid'] ;

		if(!empty($_REQUEST['bDate'])) {
			//开始和结束时间
			$bdate = explode('-',$_REQUEST['bDate']);
			$begindate = mktime(0,0,0,$bdate[1],$bdate[2],$bdate[0]);
			if(empty($_REQUEST['eDate'])) {
				$enddate = time();
			}else {
				$edate = explode('-',$_REQUEST['eDate']);
				$enddate = mktime(0,0,0,$edate[1],$edate[2]+1,$edate[0]);
			}
			$map['cTime'] = array('in',array($begindate,$enddate));
		}
		$user = D('User')->where($map)->field('id')->findAll();
		if($user == false){
			$this->error('查询失败，没有这样条件的人');
		}
		$credit['credit'] = $_POST['credit'];
		$credit['action'] = 'sys_add';
		$credit['actioncn'] = '系统操作积分';
		$credit['info'] = trim($_POST['info']);
		foreach($user as $value){
			$result[] = setUserScore($value['id'], $credit);
		}
		if (count(array_filter($result) ) == count($user)) {
			$this->success('调整积分成功');
		}else{
			$this->error('操作失败');
		}
	}
	public function setCredit() {
		//                $dao = D('CreditSetting');
		//                $dao2 = D('CreditType');
		//                //得到所有的字段名
		//                $fields = $dao->getTableFields();
		//                //获得所有的类型缓存
		//                $type = $dao2->getCreditType();
		//                foreach($fields as $key=>$value) {
		//                        if(isset($type[$value])) {
		//                                $new_fields[$value] = $type[$value];
		//                        }
		//                }
		//                return $new_fields;
	}

	/**
         * 编辑用户
         */
	public function edit() {
		$intId = intval($_GET['uid']);
		$pUser = D('User');
		$tinfo = $pUser->where('uid='.$intId)->find();
		$spaceInfo = M('space')->where('uid='.$intId)->field('isexpert')->find();
		if($tinfo && $intId) {
			$userGroups = model('UserGroup')->getGroups();
			foreach ($userGroups as $k=>$v){
				if(empty($v['gname'])) unset($userGroups[$k]);
			}
			$this->assign('usergroups',$userGroups);
			$userGroup = getSubByKey(M('user_group')->field('gid')->where("uid=$intId")->findall(),'gid');
			$this->assign('userGroup',$userGroup);
			$this->assign('info',$tinfo);
			$this->assign('isexpert',$spaceInfo['isexpert']);
			$this->display();
		}else {
			$this->error('提交错误参数');
		}
	}

	//修改用户资料
	public function doedit() {

		switch ($_REQUEST['type']) {
			case 'set':  //帐号设置
			$intUid = intval($_REQUEST['uid']);
			$pUser = D('User');
			$info = $pUser->where('uid='.$intUid)->find();
			if(!$info || !$intUid) {
				$this->error('提交错误参数');
				exit;
			}
			M('user_group')->where("uid=".$intUid)->delete();
			foreach ($_POST['userGroup'] as $value){
				$value = explode('|',$value);
				$data['gid'] = $value[0];
				$data['uid'] = $intUid;
				$data['gname'] = $value[1];
				M('user_group')->add($data);
			}

			if( intval( $_POST['isexpert'] ) ==1 || intval( $_POST['isexpert'] )==0 ){
				M('space')->setField('isexpert',intval( $_POST['isexpert'] ),'uid='.$intUid);
			}			

			addLog($this->mid, array('user'=>$info['fullname']), 'user_edit');
			
			redirect($_SERVER['HTTP_REFERER']);
			break;

			case 'movegroup':
				$gid = intval($_POST['togroupId']);
				foreach ($_POST['id'] as $value){
					model('UserGroup')->addToGroup($value,$gid);
				}				

				$num = count($_POST['id']);
				$gName = model('UserGroup')->getGroupName($gid);
				addLog($this->mid, array('num'=>$num, 'group'=>$gName), 'user_group_to');
				
				redirect($_SERVER['HTTP_REFERER']);
				break;

			case 'moveoutgroup':
				$gid = intval($_POST['togroupId']);
				foreach ($_POST['id'] as $value){
					model('UserGroup')->where("uid=$value AND gid=$gid")->delete();
				}				
				
				$num = count($_POST['id']);
				$gName = model('UserGroup')->getGroupName($gid);
				addLog($this->mid, array('num'=>$num, 'group'=>$gName), 'user_group_out');
				
				redirect($_SERVER['HTTP_REFERER']);
				break;
		}
	}

	//首页批量处理
	function doBatch() {
		$strDotype = h($_POST['dotype']);
		$userId = $_POST['id'];
		$pUser = D('User');
		if(!empty($strDotype) && is_array($userId)) {
			switch ($strDotype) {
				case 'commend':  //推荐
				foreach ($userId as $key=>$val) {
					$pUser->setField('commend','1','id='.$val);
				}
				break;

				case 'uncommend': //取消推荐
				foreach ($userId as $key=>$val) {
					$pUser->setField('commend','0','id='.$val);
				}
				break;

				case 'active': //激活
				foreach ($userId as $key=>$val) {
					$pUser->setField('active','1','id='.$val);
				}
				break;

				case 'unactive': //取消激活
				foreach ($userId as $key=>$val) {
					$pUser->setField('active','0','id='.$val);
				}
				break;

				case 'movegroup': //设置群组
				$groupId = intval($_POST['togroupId']);
				$groupInfo = D('SystemGroup')->where('id='.$groupId)->find();
				if($groupInfo || $groupId==0) {
					foreach ($userId as $key=>$val) {
						$pUser->setField('admin_level',$groupInfo['id'],'id='.$val);
					}
				}else {
					$this->error('用户组不存在');
				}

				break;
			}
			$this->success('操作成功');
		}else {
			$this->error('您提交错误请求');
		}
	}

	/*******************************  前台用户资料配置 *************************/
	function info() {

		$this->display();
	}


	/**
	 * msg
	 * 消息 [使用小HI发送]
	 * @access public
	 * @return void
	 */
	public function msg() {
		$this->display();
	}

	public function doSend() {
		if($_POST['type'] == 'msg') {
			$this->doSendMsg();
		}else if($_POST['type'] == 'email') {
			$this->doSendEmail();
		}

		addLog($this->mid, '', 'massage_send');
		
		$this->assign('jumpUrl', U('admin/User/msg'));
		$this->success('发送成功～');
	}

	public function doSendMsg() {
		$fromUserId = 1; //使用小HI发送

		$toUserIds = M('User')->where('active=1')->field('uid')->findAll();
		$toUserIds = formatArray($toUserIds, 'uid');
		$_POST['sendto_uids'] = implode(',', $toUserIds);
		$_POST['subject'] = t($_POST['subject']);
		$_POST['content'] = t($_POST['content']);
		$dao = D('Message','home');

		$r = $dao->create();
		if(false === $r) $this->error($dao->getError());

		$dao->cTime = time();
		$dao->fromUserId = $fromUserId;
		$server = x('Notify');
		foreach($toUserIds as $uid){
			$dao->toUserId = $uid;
			$r = $dao->add();
			if($r){
				$title['title']  = $_POST['subject'];
				$body['content'] = $_POST['content'];
				$server->put('home_sendmessage',$uid,$title,$body,$fromUserId);
			}
		}
	}

	public function doSendEmail() {
		$sendto = M('User')->where('active=1')->field('email')->findAll();
		$sendto = formatArray($sendto, 'email');
		$res    = Service('Mail')->send_email($sendto, t($_POST['subject']), $_POST['content']);

		$this->assign('jumpUrl', U('admin/User/msg'));
		if($res) {
			$this->success('发送成功～');
		}else {
			$this->error('发送失败～');
		}
	}
	/**
		1，验证新工号和旧工号,并获取新ID
		新工号UNAME = $newid;
		旧工号UNAME = $oldid;

		2，删除新工号数据，修改旧工号数据
		DELETE FROM `ts_user` WHERE uname=$oldid LIMIT 1;
		UPDATE FROM `ts_user` SET uname=$oldid LIMIT 1; 

		3，删除新数据
		DELETE FROM `ts_space` WHERE uid='$newid';
		DELETE FROM `ts_space_info` WHERE uid='$newid';
		DELETE FROM `ts_space_search` WHERE uid='$newid';
		DELETE FROM `ts_space_visitor` WHERE uid='$newid';
		DELETE FROM `ts_follow` WHERE uid='$newid' OR aimId='$newid';
	**/
	public function doChangeCardId() {

		$model		=	D('User');
		$oldid		=	t($_POST['oldid']);
		$newid		=	t($_POST['newid']);

		$olduser	=	$model->where("uname='{$oldid}'")->find();
		$newuser	=	$model->where("uname='{$newid}'")->find();

		if(!$olduser){
			$this->error('请确认填写正确，旧用户不存在！');
		}

		if(!$newuser){
			$this->error('请确认填写正确，新用户不存在！');
		}

		$olduid =	$olduser['uid'];
		$newuid	=	$newuser['uid'];
		$model->startTrans();
		//删除新工号的所有用户数据
		$model->execute("DELETE FROM ".C('DB_PREFIX')."user WHERE uname='{$newid}' LIMIT 1 ");
		//将旧工号的用户名改成新工号
		$model->execute("UPDATE ".C('DB_PREFIX')."user SET uname='{$newid}' WHERE uid='{$olduid}' LIMIT 1 ");
		$model->execute("UPDATE ".C('DB_PREFIX')."space SET cardId='{$newid}' WHERE uid='{$olduid}' LIMIT 1 ");
		//将新工号的数据切换到旧工号
		$model->execute("DELETE FROM ".C('DB_PREFIX')."space WHERE uid='{$newuid}'");
		$model->execute("DELETE FROM ".C('DB_PREFIX')."space_info WHERE uid='{$newuid}'");
		$model->execute("DELETE FROM ".C('DB_PREFIX')."space_search WHERE uid='{$newuid}'");
		$model->execute("DELETE FROM ".C('DB_PREFIX')."space_visitor WHERE uid='{$newuid}'");
		$model->execute("DELETE FROM ".C('DB_PREFIX')."follow WHERE uid='{$newuid}' OR aimId='{$newuid}'");
		$result	=	$model->commit();
		if($result){
			addLog($this->mid, '', 'uname_change');
			
			$this->success('切换成功！');
		}
	}
	
	//任务计划发送邮件列表
	public function cron_send_email() {
		//读邮件列表，读出200条，发送
		$xmail	=	model('Xmail');
		$maillist	=	$xmail->where('status<2')->order('status desc')->limit('200')->findAll();
		if($maillist){
			foreach($maillist as $v){
				$result	=	X('Mail')->send( $v['to_mail'], $v['subject'], $v['content']);
				if($result){
					$success[]	=	$v['id'];
				}else{
					$fail[]	=	$v['id'];
				}
			}
			$xmail->setSuccess($success);
			$xmail->setFail($fail);
		}else{
			return false;
		}
	}
}
?>